import React, { useEffect, useState ,Key} from "react";
import { Row, Col, Card, Tree, Tag, Pagination, Table,Button,message } from "antd";
import { useNavigate,useParams } from "react-router-dom";
import {
  hosDepartmentListRequest,
  hosScheduleRuleRequest,
  findScheduleListRequest,
} from "@/api/hospital/hospitalList";
import type { 
  hosDepartmentListType,
  bookingScheduleListType,
  findScheduleListType,
} from "@/api/hospital/model/hospitalListTypes";
export default function HospitalSchedule() {
  const navigate=useNavigate();
  //接收params参数
  const { hoscode } = useParams();
  // console.log(hoscode);

  //定义一个控制treeData的state
  const [treeData, setTreeData] = useState<hosDepartmentListType>([]);
  //定义一个时间排班规则的当前页码
  const [page, setPage] = useState(1);
  //定义一个时间排班规则的每页条数
  const [limit, setLimit] = useState(3);
  //定义当前科室的排班规则
  const [scheduleRule, setScheduleRule] = useState<bookingScheduleListType>([]);
  //定义当前科室的排班规则总条数
  const [total, setTotal] = useState(0);
  //定义表格的数据
  const [sourceData, setSourceData] = useState<findScheduleListType>([]);
  const [workDate,setWorkDate]=useState("");
  const [depcode,setDepcode]=useState("");



  //1.定义一个请求科室列表的函数
  const getDepartmentList = async () => {
    const result = await hosDepartmentListRequest(hoscode as string);
    //把获取到的科室的数据交给state
    setTreeData(result);

    return result;
  };
  //2.定义一个请求科室排班的函数
  const getScheduleRule = async (
    depcode: string,
    page:number,
    limit:number
    ) => {
    const result = await hosScheduleRuleRequest({
      page: page,
      limit: limit,
      hoscode: hoscode as string,
      depcode: depcode,
    });
    setTotal(result.total);
    setScheduleRule(result.bookingScheduleList);
    return result;
  };

  //3.定义一个请求排班详情的函数
  const getFindScheduleList = async (workDate: string, depCode: string) => {
    const result = await findScheduleListRequest({
      hoscode: hoscode as string,
      depcode: depCode,
      workDate: workDate,
    });
    // console.log(result);

    setSourceData(result);
  };

  //初始化请求
  useEffect(() => {
    const getData = async () => {
      //1.请求科室列表 得到科室列表的数据
      const departmentList = await getDepartmentList();
      //2.根据科室数据获取初始的科室信息(默认第一个)
      const initDepCode = (
        departmentList[0].children as hosDepartmentListType
      )[0].depcode;
      // 把初始的depcode设置给state
      setDepcode(initDepCode);
      //3.把初始的科室信息传递给 请求排班列表的函数,得到排班列表
      const scheduleRule = await getScheduleRule(initDepCode,page,limit);
      //4.根据排班列表,得到初始的排班列表的时间(默认第一个)
      const initWordDate = scheduleRule.bookingScheduleList[0].workDate;
      //5.根据排班列表的初始时间 请求 详细信息
      await getFindScheduleList(initWordDate, initDepCode);
    };

    getData();
  }, []);


  //1.改变页码的事件回调函数
  const changePageHandle = async (page: number, limit: number) => {
    setPage(page);
    setLimit(limit);

    //发送科室排班的请求
    const scheduleRuleResult = await getScheduleRule(depcode,page,limit);
    // 根据科室排班请求数据的第一个请求详细信息
    const firstWorkDate =scheduleRuleResult.bookingScheduleList[0].workDate;
    setWorkDate(firstWorkDate);
    //根据第一个科室排班的信息获取表格详细信息
    getFindScheduleList(firstWorkDate,depcode);
  
  };

  //2.点击tree的事件回调函数
  const treeSelectHandle = async (depCodeArr: Key[]) => {
   if(depCodeArr.length ===0){
    return;
   }
   try{
    const depcode = depCodeArr [0] as string;
    // 把当前的科室保存在状态中
    setDepcode(depcode);
    //根据点击的值，请求科室排班信息
    const scheduleRuleResult=await getScheduleRule (depcode,page,limit);
    const firstWorkDate=scheduleRuleResult.bookingScheduleList[0].workDate;
    // 根据第一个科室排班的信息，获取表格详细信息
    getFindScheduleList(firstWorkDate,depcode);
    } catch(e){
      message.error("没有数据");
      // 清空表格
      setSourceData([]);
    }
  };

  //3.点击事件的时间回调函数
  const scheduleRuleHandle = (workDate: string) => {
    return () => {
      setWorkDate(workDate);
      // getFindScheduleList();

      //发送详细请求
      getFindScheduleList(workDate,depcode);
    };
  };

  //table结构
  const columns = [
    {
      title: "序号",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号源时间",
      dataIndex: "workDate",
    },
    {
      title: "可预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "挂号费用",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
    },
  ];
  const treeStyle = {
    border: "1px solid #000",
    height: "480px",
    overflow: "auto",
  };
  return (
    <Card>
      <p>选择:北京协和医院/多发性硬化专科门诊/2022-04-08</p>
      <Row gutter={20}>
        <Col span={5}>
          <div>
            <Tree
              //antd目前没有很好的解决treeData修改字段后的类型控制,临时解决方案是断言为[]
              treeData={treeData as []}
              style={treeStyle}
              fieldNames={{ title: "depname", key: "depcode" }}
              expandedKeys={["a4e171f4cf9b6816acdfb9ae62c414d7"]}
              onSelect={treeSelectHandle}
            />
          </div>
        </Col>
        <Col span={19}>
          <div style={{ marginBottom: "20px" }}>
            {scheduleRule.map((item) => {
              return (
                <Tag
                  key={item.workDate}
                  onClick={scheduleRuleHandle(item.workDate)}
                  style={{ cursor: "pointer" ,
                  background:item.workDate===workDate ? "#1DA57A":"",
                }}
                >
                  <p>{item.workDate}</p>
                  <p>
                    {item.availableNumber}/{item.reservedNumber}
                  </p>
                </Tag>
              );
            })}
          </div>
          <Pagination
            current={page}
            pageSize={limit}
            total={total}
            onChange={changePageHandle}
          />

          <Table
            columns={columns}
            style={{ marginTop: "20px" }}
            dataSource={sourceData}
            rowKey={"id"}
            bordered
            pagination={false}
          ></Table>

          <Button
            onClick={() => {
              navigate(-1);
            }}
            style={{ marginTop: "30px" }}
          >
            返回
          </Button>
        </Col>
      </Row>
    </Card>
  );
}
